package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 * 
 * @author chenming
 * @date 2025-05-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表到redis
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IoTDAClient client;
    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        /*if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }*/

        //接收集合
        List<ProductSummary> productList = response.getProducts();
        //存储到redis
        redisTemplate.opsForValue().set(RedisKeyConstants.IOT_ALL_PRODUCT_LIST, productList);
    }

    /**
     * redis查询所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从redis查询所有产品列表
        List<ProductSummary> productList = (List<ProductSummary>) redisTemplate.opsForValue().get(RedisKeyConstants.IOT_ALL_PRODUCT_LIST);

        //判断List是否为空，如果为空，则返回空集合
        if (CollectionUtil.isEmpty(productList)){
            return List.of();
        }
        //2．转换为V0
        List<ProductVo> productVoList = BeanUtil.copyToList(productList, ProductVo.class);
        return productVoList;
    }

    /**
     * 注册设备
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        //1.判断设备名称name是否重复，（如果重复，抛出异常，终止运行）
        long countName = count(new LambdaQueryWrapper<Device>()
                .eq(StrUtil.isNotBlank(dto.getDeviceName()), Device::getDeviceName, dto.getDeviceName()));
        if (countName > 0){
            throw new BaseException("设备名称重复");
        }
        //2.检验设备标识码nodeId是否重复
        long countNodeId = count(new LambdaQueryWrapper<Device>()
                .eq(StrUtil.isNotBlank(dto.getNodeId()), Device::getNodeId, dto.getNodeId()));
        if (countNodeId > 0){
            throw new BaseException("设备标识码重复");
        }
        //3.校验同一位置（位置类型+绑定位置）是否绑定了同一类产品（产品唯一标识）
        long countProduct = count(new LambdaQueryWrapper<Device>()
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(dto.getPhysicalLocationType() != null,Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getProductKey, dto.getProductKey()));
        if (countProduct > 0){
            throw new BaseException("同一位置（位置类型+绑定位置）只能绑定同一类产品");
        }
        //4.在iot平台中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());

        //设置设备的秘钥
        String scret= UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(scret);
        body.setAuthInfo(authInfo);
        request.withBody(body);

        //发送请求
        String iotId="";
        try {
            AddDeviceResponse response = client.addDevice(request);
            iotId=response.getDeviceId();
        } catch (Exception e) {
            throw new BaseException("设备注册失败");
            //打印异常
//            e.printStackTrace();
        }

        //5.设备数据保存到数据库
        //对象属性拷贝
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(scret);
        device.setIotId(iotId);
        //如果device的localtionType字段为0，则设置将bingLocalation为赋值给deviceDescription
        if (device.getLocationType() == 0){
            device.setDeviceDescription(device.getBindingLocation());
            device.setPhysicalLocationType(-1);
        }

        save(device);
    }

    /**
     * 查询设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1．先查询I0T平台，得到设备详情：：设备状态、激活时间
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);

        String deviceStatus="";
        String activeTimeStr="";
        try {
            ShowDeviceResponse response = client.showDevice(request);
            //设备状态、激活时间
            deviceStatus=response.getStatus();
            activeTimeStr=response.getActiveTime();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("查询设备详情失败");
        }

        //2.再查数据库设备表，得到设备详情
        Device device=getOne(new LambdaQueryWrapper<Device>()
                .eq(Device::getIotId, iotId)
        );

        //3.组装V0返回
        DeviceDetailVo vo=BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceStatus(deviceStatus);

        //需要单独的组装时间
        //因为华为云返回的激活时间格式为"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"，需要转换为yyyy-MM-dd HH:mm:ss
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(activeTime);
        }
        return vo;
    }

    /**
     * 查看设备上报的数据
     * @param iotId
     * @return
     */
    @Override
    public List<Map> queryServiceProperties(String iotId) {
        //1.先查询I0T平台，得到设备最新上报的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);

        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);

            //2.解析响应数据
            Object properties = response.getShadow()
                    .get(0)
                    .getReported()
                    .getProperties();
            //json对象
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            //上报时间
            String eventTimeStr = response.getShadow().get(0).getReported().getEventTime();

            //3.封装数据
            List list = new ArrayList<>();

            //需要对日期格式进行单独处理
            //处理上报时间日期
            LocalDateTime activeTime=LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            jsonObject.forEach((k,v)->{
                Map<String,Object> map = new HashMap<>();
                map.put("functionId",k);
                map.put("value",v);
                map.put("eventTime",eventTime);
                list.add(map);
            });
            return list;

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("查询设备详情失败");
        }
    }

    /**
     * 修改设备信息
     * @param device
     */
    @Override
    public void editDevice(Device device) {

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        /*Device deviceOne = getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, device.getIotId()));
        if (deviceOne == null){
            throw new BaseException("设备不存在");
        }*/

        Long currentId = device.getId();
        Device existingDevice = getOne(new LambdaQueryWrapper<Device>().eq(Device::getId, currentId));
        if (existingDevice == null) {
            throw new BaseException("设备不存在");
        }
        // 获取当前设备的 iotId（用于云端操作）
        String iotId = existingDevice.getIotId();
        if (iotId == null || iotId.isEmpty()) {
            throw new BaseException("设备IoT ID为空，无法修改云端信息");
        }
        // 校验 deviceName 是否重复(不等于当前id并且还有相同的，统计其数量)
        if (device.getDeviceName() != null && !device.getDeviceName().equals(existingDevice.getDeviceName())) {
            long countByName = count(new LambdaQueryWrapper<Device>()
                    .eq(Device::getDeviceName, device.getDeviceName())
                    .ne(Device::getId, currentId));
            if (countByName > 0) {
                throw new BaseException("设备名称已存在，请重新输入");
            }
        }
        // 校验 deviceDescription 是否重复（如果字段允许为空，则加非空判断）
        if (device.getDeviceDescription() != null && !device.getDeviceDescription().equals(existingDevice.getDeviceDescription())) {
            long countByDescription = count(new LambdaQueryWrapper<Device>()
                    .eq(Device::getDeviceDescription, device.getDeviceDescription())
                    .ne(Device::getId, currentId));
            if (countByDescription > 0) {
                throw new BaseException("位置备注已存在，请重新输入");
            }
        }

        //修改云端的设备名
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(device.getDeviceName());
        request.withBody(body);
        try {
            UpdateDeviceResponse response = client.updateDevice(request);
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            e.printStackTrace();
            throw new BaseException("修改设备失败");
        }

        //对device.getLocationType()进行比较是否为0，若为0将physicalLocationType改为-1
        if (device.getLocationType() == 0){
            device.setPhysicalLocationType(-1);
        }
        updateById(device);
    }
    /* //1.判断设备名称name是否重复，（如果重复，抛出异常，终止运行）
        long countName = count(new LambdaQueryWrapper<Device>()
                .eq(StrUtil.isNotBlank(device.getDeviceName()), Device::getDeviceName, device.getDeviceName()));
        if (countName > 0){
            throw new BaseException("设备名称重复");
        }
        //2.检验设备标识码nodeId是否重复
        long countNodeId = count(new LambdaQueryWrapper<Device>()
                .eq(StrUtil.isNotBlank(device.getNodeId()), Device::getNodeId, device.getNodeId()));
        if (countNodeId > 0){
            throw new BaseException("设备标识码重复");
        }
        //3.校验同一位置（位置类型+绑定位置）是否绑定了同一类产品（产品唯一标识）
        long countProduct = count(new LambdaQueryWrapper<Device>()
                .eq(device.getPhysicalLocationType() != null,Device::getPhysicalLocationType, device.getPhysicalLocationType())
                );
        if (countProduct > 0){
            throw new BaseException("同一位置（位置类型+绑定位置）只能绑定同一类产品");
        }*/

    /**
     * 删除设备
     * @param iotId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(String iotId) {
        //先对数据库操作，再删除云平台，就可以回滚了
        deviceMapper.delete(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));

//        Device device = getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            e.printStackTrace();
            throw new BaseException("删除设备失败");
        }

//        if (device == null){throw new BaseException("设备不存在");}
        /*if (
            //根据iotId查询的对象为空时
                deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId)) == null
        ){
            throw new BaseException("设备不存在");
        }*/
//        deleteDeviceById(device.getId());

    }

    /**
     * 查询产品信息
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {

        if (StringUtils.isEmpty(productKey)){
            throw new BaseException("产品标识码不能为空");
        }

        //1.根据产品的标识查询I0T平台产品的详情数据
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);

        List<ServiceCapability> serviceCapabilities;

        try {
            ShowProductResponse response = client.showProduct(request);
            //2．解析结果并返回
            serviceCapabilities = response.getServiceCapabilities();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口，查询产品失败");
        }

        //3.处理好空校验
        if (CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(List.of());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
